package com.zy.dp.composite.example6;

import java.util.ArrayList;
import java.util.List;

public class Composite extends Component
{
	private List<Component> childComponents = null;
	private String name = "";

	public Composite(String name)
	{

		this.name = name;
	}

	@Override
	public String getName()
	{
		return this.name;
	}

	public void addChild(Component child)
	{

		if (childComponents == null)
		{
			childComponents = new ArrayList<Component>();
		}

		childComponents.add(child);

		if (this.getComponentPath() == null
				|| this.getComponentPath().trim().length() == 0)
		{
			this.setComponentPath(this.name);
		}

		if (this.getComponentPath().startsWith(child.getName() + "."))
		{
			throw new IllegalArgumentException("在本通路上，组件'" + child.getName()
					+ "‘已被添加过了");
		}
		else if (this.getComponentPath().indexOf("." + child.getName()) < 0)
		{
			String componentPath = this.getComponentPath() + "."
					+ this.getName();

			child.setComponentPath(componentPath);
		}

		else
		{
			throw new IllegalArgumentException("在本通路上，组件'" + child.getName()
					+ "‘已被添加过了");
		}

	}

	@Override
	public void printStruct(String preStr)
	{
		System.out.println(preStr + "-" + this.name);

		if (this.childComponents != null)
		{
			preStr += " ";
			for (Component c : childComponents)
			{
				c.printStruct(preStr);
			}
		}

	}

}
